<script setup lang="ts">
defineOptions({
  name: "uploadFiles"
});
import { ref, reactive, onMounted, getCurrentInstance, watch } from "vue";
import type { FormInstance, FormRules } from "px-ui";
import { PxMessage } from "px-ui";
import importFiles from "@/views/common/components/importFiles/index.vue";
import { queryChildByTypeCodeAndItemValue, importAddDrug } from "@/api/machineClass";
import { wasteWaterimportData } from "@/api/waterQualityDetection";
import { querySystemSelect } from "@/api/equip/archive";
import { useThrottleFn } from "@vueuse/core";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import { throttleDelay as delay } from "@/utils/constant";
import { getToken } from "@/utils/auth";

interface Props {
  // 弹框类型 add 新增   edit 编辑
  type?: "add" | "edit";
  id?: string;
}

const props = withDefaults(defineProps<Props>(), {});

const dialogVisible = defineModel({ type: Boolean, default: false });

interface RuleForm {
  dosingPersonId: string;
  dosingPerson: string;
  dosingOrganization: string;
  responsiblePersonId: string;
  responsiblePerson: string;
}
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  dosingPersonId: "",
  dosingPerson: "",
  dosingOrganization: "",
  responsiblePersonId: "",
  responsiblePerson: ""
});

const organizationArr = ref<any>([]);
const locationArr = ref<any>([]);
const peopleList = ref<any>([]);

const rules = reactive<FormRules<RuleForm>>({
  dosingOrganization: [{ required: true, message: "请选择检测机构", trigger: "change" }],
  dosingPersonId: [{ required: true, message: "请选择加药人", trigger: "change" }],
  responsiblePersonId: [{ required: true, message: "请选择本课负责人", trigger: "change" }]
});

const importFile = ref<any>({});
const gasNameOptions = ref({});

const defaultProps = {
  children: "children",
  label: "name",
  value: "code"
};

const { proxy }: any = getCurrentInstance();
const { VITE_FANRUAN_BASE_URL, VITE_SERVE_API_STATIC_URL } = import.meta.env;
const downloadFn = () => {
  let Token = getToken().accessToken || "";
  // proxy.download("post", "/operation/api/v1/water/testQuality/pwMetalImpurity/export", queryParams.value, "水质检测-纯水金属阴阳离子.xlsx");
  let url = `${VITE_FANRUAN_BASE_URL}/webroot/decision/view/report?viewlet=water%252F%25E5%25BA%259F%25E6%25B0%25B4%25E6%25B0%25B4%25E8%25B4%25A8%25E6%25A3%2580%25E6%25B5%258B%25E6%258A%25A5%25E8%25A1%25A8.cpt&token=${Token}&from=1999-01-01&to=1999-01-02&location&format=excel&extype=simple&facCode=${localStorage.getItem("facCode") || ""}&apiHost=${VITE_SERVE_API_STATIC_URL}`;
  window.location.href = url;
};

const emits = defineEmits(["submit"]);

const cancelHandler = () => {
  dialogVisible.value = false;
};

const submitHandler = useThrottleFn(async () => {
  const { file = "" } = importFile.value;
  console.log("importFile.value  ", importFile.value);
  // return;
  if (!file) {
    PxMessage.error("请上传 报告 ！");
    return;
  } else {
    let fileFormData = new FormData();
    fileFormData.append("file", file);
    let res = await wasteWaterimportData(fileFormData);
    emits("submit", res);
    dialogVisible.value = false;
  }
  // if (!ruleFormRef.value) return;
  // await ruleFormRef.value.validate(async (valid, fields) => {
  //   if (valid) {
  //     let fileFormData = new FormData();
  //     for (const key in ruleForm) {
  //       fileFormData.append(key, ruleForm[key]);
  //     }
  //     // const { file = "" } = importFile.value;
  //     file && fileFormData.append("file", file);
  //     await importAddDrug(fileFormData);
  //     emits("submit");
  //     dialogVisible.value = false;
  //     // ruleFormRef.value.resetFileds();
  //     // importFile.value = {};
  //   } else {
  //     console.error("error submit!", fields);
  //   }
  // });
}, delay);

const samplePersonIdChange = (val: any) => {
  ruleForm.dosingPerson = peopleList.value.filter((item: any) => item.value === val)[0].label;
};
const responsiblePersonIdChange = (val: any) => {
  ruleForm.responsiblePerson = peopleList.value.filter((item: any) => item.value === val)[0].label;
};
const fsxlsx = ref("");
onMounted(() => {
  fsxlsx.value = proxy.useGetStaticUrl(`/ifp-web-static/file/xlsx/附件4.2 废水水质检测导入模板.xlsx`);
});
const init = async () => {
  gasNameOptions.value = await querySystemSelect({ factoryArea: "", className: "MACHINE" });
};
</script>

<template>
  <px-dialog v-model="dialogVisible" draggable clickHideContent title="导入报告" :width="600">
    <div class="import-bottle">
      <div class="import-bottle-title">
        上传前请先
        <!-- <span class="download" @click="downloadFn"> 下载模板 </span> -->
        <a :href="fsxlsx" download="废水水质检测导入模板.xlsx"><span class="download"> 下载模板 </span></a>
        ，填写完成后导入数据
      </div>
      <div class="import-bottle-upload">
        <importFiles v-model="importFile" isNotImmediateUpload />
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <px-button @click="cancelHandler">取消</px-button>
        <px-button type="primary" @click="submitHandler"> 确认 </px-button>
      </span>
    </template>
  </px-dialog>
</template>

<style lang="scss" scoped>
.import-bottle {
  .import-bottle-title {
    box-sizing: border-box;
    display: flex;
    align-items: center;
    width: 100%;
    height: 40px;
    padding-left: 16px;
    margin-bottom: 24px;
    line-height: 1;
    color: #333;
    background-color: #fef5e6;
    border: 1px solid #f7b648;
    border-radius: 6px;

    .download {
      color: #3b82f6;
      cursor: pointer;
    }
  }

  .import-bottle-upload {
    width: 100%;
    margin-bottom: 24px;
  }
}

:deep(.px-form-item) {
  width: 100%;

  .px-form-item__content {
    .px-input,
    .px-select,
    .px-date-picker,
    .px-time-picker,
    .px-tree-select {
      width: 100%;
    }
  }
}
</style>
